import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import matplotlib

matplotlib.rc("font", family='Source Han Sans CN', weight="regular", size="10")

file_path = "csv/911.csv"
df = pd.read_csv(file_path)

# 新增分类列
title_series = df["title"].str.split(":")
title_list = [i[0] for i in title_series]
df["category"] = np.array(title_list).reshape((df.shape[0], 1))

# 将时间列转换成时间序列并设置为索引
df["timeStamp"] = pd.to_datetime(df["timeStamp"])
df.set_index("timeStamp", inplace=True)

plt.figure(figsize=(20, 8), dpi=80)
plt.xlabel("时间")
plt.ylabel("数量")
plt.title("911电话报警类型随月份变化统计图", weight="bold", size="16")

# 遍历分组后的结果，对时间重采样并分别画图
for group_name, group_data in df.groupby(by="category")["title"]:
    resample_time = group_data.resample("M").count()
    x = [i.strftime("%Y-%m") for i in resample_time.index]
    plt.plot(x, resample_time.values, label=group_name)
plt.xticks(range(len(x)), x, rotation=45)
plt.legend()
plt.show()
